<template>
  <div class="app-container">
    <div class="top-bar-container">
      <el-row>
        <el-col :span="16">
          <div class="search-container">
            <search-form @search-submit="getAgenciesList">
              <search-input v-model="listQuery.id" placeholder="ID" />
              <search-input v-model="listQuery.name" placeholder="名称" />
            </search-form>
          </div>
        </el-col>
        <el-col :span="8">
          <el-row type="flex" justify="end">
            <el-button type="primary" size="small" icon="el-icon-plus" @click="handleCreateAgencies">新增机构
            </el-button>
          </el-row>
        </el-col>
      </el-row>
    </div>

    <el-table v-loading="listLoading" :data="list" border fit stripe highlight-current-row>
      <el-table-column
        align="center"
        label="ID"
        prop="id"
      />

      <el-table-column align="center" label="名称" prop="name" />

      <el-table-column align="center" label="管辖范围" prop="areaName" />

      <el-table-column align="center" label="创建时间" prop="createdTime" />

      <el-table-column align="center" label="更新时间" prop="updatedTime" />

      <el-table-column
        align="center"
        fixed="right"
        label="操作"
        width="280"
      >
        <template v-slot="scope">
          <el-button-group>
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-edit"
              title="编辑"
              @click="handleEditAgenciesRow(scope.$index)"
            >编辑
            </el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              title="删除"
              @click="handleDeleteAgenciesRow(scope.$index)"
            >删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>

    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getAgenciesList"
    />

    <el-dialog
      :title="editForm.id ? '编辑机构' : '新增机构'"
      :visible.sync="dialogEditVisible"
      width="500px"
      @close="handleEditFormDialogClose"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="editRules"
        class="edit-form"
        autocomplete="on"
        label-position="right"
      >

        <el-form-item prop="areaCode" label="管辖范围" label-width="80px">
          <el-cascader
            :options="divisionList"
            :props="divisionProps"
            clearable
            :show-all-levels="false"
            @change="handleDivisionChange"
          />
        </el-form-item>

        <el-form-item prop="name" label="名称" label-width="80px">
          <el-input v-model="editForm.name" />
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEditVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSaveAgencies">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination/index.vue'
import SearchForm from '@/components/SearchForm/index.vue'
import SearchInput from '@/components/SearchForm/SearchInput/index.vue'
import {
  adminAgenciesCheckAvailable,
  adminAgenciesCreate,
  adminAgenciesDelete,
  adminAgenciesSearch,
  adminAgenciesUpdate
} from '@/api/rest/agencies'
import { yesNoStatusList } from '@/utils/dict'
import { elRequiredRule } from '@/utils/el-validator'
import { adminDivisionListByParentId } from '@/api/rest/division'

const initForm = {
  id: null,
  name: null,
  areaCode: null
}

export default {
  name: 'AgenciesList',
  components: { SearchInput, Pagination, SearchForm },
  data() {
    const validateNameAvailable = (rule, value, callback) => {
      return adminAgenciesCheckAvailable(this.editForm.id, value).then(resp => {
        if (!resp.data.available) {
          callback(new Error('名称已存在'))
        } else {
          callback()
        }
      })
    }

    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        id: null,
        name: null,
        page: 1,
        limit: 10
      },
      editForm: { ...initForm },
      editRules: {
        name: [elRequiredRule, { trigger: 'blur', validator: validateNameAvailable }],
        areaCode: [elRequiredRule]
      },
      yesNoStatusList: yesNoStatusList,
      dialogEditVisible: false,
      divisionList: [],
      cityList: [],
      areaList: [],
      divisionSelected: [],
      divisionProps: {
        expandTrigger: 'hover',
        lazy: true,
        checkStrictly: true,
        lazyLoad(node, resolve) {
          const { value, level } = node
          if (level >= 3) {
            resolve([])
            return
          }
          adminDivisionListByParentId(value ?? 0)
            .then(response => {
              const list = []
              response.data.forEach(item => {
                list.push({ value: item.id, label: item.areaName, leaf: level >= 2 })
              })
              resolve(list)
            })
        }
      }
    }
  },
  created() {
    this.getAgenciesList()
  },
  methods: {
    getAgenciesList() {
      this.listLoading = true
      adminAgenciesSearch(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleEditAgenciesRow(index) {
      this.editForm = { ...this.list[index] }
      this.dialogEditVisible = true
    },
    handleDeleteAgenciesRow(index) {
      const data = this.list[index]
      this.$confirm('此操作将删除机构, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        adminAgenciesDelete(data.id).then(() => {
          this.$message({
            type: 'success',
            message: '删除机构成功'
          })
          this.getAgenciesList()
        }).catch(() => {
        })
      })
    },
    handleCreateAgencies() {
      this.editForm = { ...initForm }
      this.dialogEditVisible = true
    },
    handleSaveAgencies() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          if (this.editForm.id) {
            adminAgenciesUpdate(this.editForm).then(response => {
              this.$message({
                message: '编辑机构成功',
                type: 'success'
              })
              this.getAgenciesList()
              this.dialogEditVisible = false
            })
          } else {
            adminAgenciesCreate(this.editForm).then(response => {
              this.$message({
                message: '新增机构成功',
                type: 'success'
              })
              this.getAgenciesList()
              this.dialogEditVisible = false
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleEditFormDialogClose() {
      this.$refs.editForm.clearValidate()
    },
    handleDivisionChange(value) {
      this.editForm.areaCode = value[value.length - 1]
    }
  }
}
</script>
<style scoped>
</style>

